<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
    <template v-slot:message_param="{row}">
      <div class="el-form-item" v-for="(label,k) in row.param_config">
        <label class="el-form-item__label" style="width: 8em;">{{label}}</label>
        <div class="el-form-item__content">
          <input type="hidden" :name="row.name+'['+k+']'" :value="row.value[k]">
          <div class="flex" style="width: 100%;">
            <text_one class="max" v-model:value="row.value[k]"></text_one>
            <select_one style="width: 200px;" :config="row.config" placeholder="插入变量" @update:value="row.value[k]+='`'+$event+'`'"></select_one>
          </div>
        </div>
      </div>
    </template>
  </forms>
</template>

<script>
import s94Mjs from "s94-js";
import {iframe} from "@/js/tool.js";
import {ajax} from "@/js/api_tool.js";

export default {
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    let forms_config = {
      event_name: {label:'触发事件',name:'event_name',type:'select_one',config:[],tips:''},
      model_id: {label:'模型',name:'model_id',type:'select_one',config:[],tips:'',value: this.$get('model_id','')},
      throw: {label:'抛出异常',name:'throw',type:'radio_switch',tips:'如果抛出移除，执行方法出错时，会中断程序',value:0},
      function: {label:'执行方法',name:'function',type:'select_one',config:[],tips:''},
    }
    if (id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      function_map: [],
      field_map: [],
    }
  },
  methods: {
    onsubmit(formData){
      let url = this.id ? `/admin/event/edit?id=`+this.id : '/admin/event/add';
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('event/index', '$refs.list_url.list');
          iframe.hide('event/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    change_function(){
      let app = this;
      let func = this.config.function.value;
      let params = !func || !app.function_map[func] ? [] : app.function_map[func].param;
      s94Mjs.each(app.field_map, function(v,k){
        if (~params.indexOf(k)){
          app.config[k].remove = false;
        }else {
          app.config[k].remove = true;
        }
      })
    },
    change_message_id(){
      let app = this;
      let id = app.config.message_id.value;
      let old_v = app.config.message_param.value || {};
      app.config.message_param.value = {};
      app.config.message_param.param_config = {};
      ajax('/admin/message_template/info?id='+id, function(res){
        let param_map = JSON.parse(res.data.param);
        s94Mjs.each(param_map, function (label, k){
          app.config.message_param.value[k] = old_v[k] || '';
        })
        app.config.message_param.param_config = param_map;
        return false;
      })
    },
  },
  watch:{
    'config.function.value'(func){
      let app = this;
      this.change_function();
    },
    'config.message_id.value'(id, oldid){
      if (id!=oldid) this.change_message_id();
    },
    'config.event_name.value'(v, oldV){
      let is_model = ~['ModelDataAdd','ModelDataEdit'].indexOf(v);
      let is_order = ~['OrderCancel','OrderCreate','OrderPay','OrderPayFail','OrderPaySuccess','OrderDeliver','OrderTake','OrderUse','OrderOver',
        'OrderRefundApply','OrderRefundAgree','OrderRefundRefuse','OrderRefundReturnDeliver','OrderRefundRefund','OrderRefundFail','OrderRefundSuccess'].indexOf(v);
      if (is_model || is_order){
        this.config.model_id.type = 'select_one';
      }else {
        this.config.model_id.type = 'hidden';
        this.config.model_id.value = 0;
      }
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/event/info?id='+this.id, cache:true}, (res)=>{
        let param = JSON.parse(res.data.param);
        delete res.data.param;
        app.$refs['forms'].init(res.data);
        setTimeout(function(){
          s94Mjs.each(app.field_map, function(row,k){
            if (app.config[k].remove) return;
            let ms = app.config[k].name.match(/param\[(\d+)\]/);
            if (ms && param[ms[1]]){
              app.config[k].value = param[ms[1]];
            }
          })
        },10)
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('edit');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
    ajax({url:'/admin/model/list',cache:true},function(res){
      let config = app.decode_config(res.data.list, {content_key:'alias', value_key:'id'});
      app.config.model_id.config = config;
      return false
    })
    ajax({url:'/admin/event/function_config',cache:true},function (res){
      app.config.event_name.config = res.data.event_map;
      app.function_map = res.data.function_map;
      app.field_map = res.data.field_map;
      app.config.function.config = [];
      s94Mjs.each(app.function_map, function(v,k){
        app.config.function.config.push({content:v.content, value:k});
      })
      s94Mjs.each(app.field_map, function(row,k){
        app.config[k] = row;
        app.config[k].remove = true;
      })
      return false;
    })
  }
}
</script>
